package com.zyht.common.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.Inet4Address;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSON;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.wx.core.vo.response.Fans;

/**
 * 工具类
 *
 * @author LL
 */
public class CommonUtils {


    /**
     * String\List\Set\Map为空判断 null "null" "" 都认为是true
     *
     * @param obj obj	
     * @return b
     */
    @SuppressWarnings("rawtypes")
	public static boolean isEmpty(Object obj) {
        if (obj == null)
            return true;

        if (obj instanceof String) {
            String str = (String) obj;
            return str.trim().length() == 0 || str.toLowerCase().equals("null");
        } else if (obj instanceof List) {
            List ls = (List) obj;
            return ls.size() == 0;
        } else if (obj instanceof Set) {
            Set ls = (Set) obj;
            return ls.size() == 0;
        } else if (obj instanceof Map) {
            Map ls = (Map) obj;
            return ls.size() == 0;
        } else if (obj instanceof Object[]) {
            Object[] ls = (Object[]) obj;
            return ls.length == 0;
        }
        return false;
    }

    public static boolean isNotEmpty(Object obj) {
        return !isEmpty(obj);
    }

    /**
     * 只要有一个不为空，就返回true
     *
     * @param obj 判断参数
     * @return bo
     */
    public static boolean isNotNull(Object... obj) {
        for (Object o : obj) {
            if (CommonUtils.isNotEmpty(o)) {
                return true;
            }
        }

        return false;
    }

    /**
     * 获取指定长度的字符串
     *
     * @param str      字符
     * @param length   长度
     * @param encoding 编码
     * @return str
     */
    public static String getSpecifiedLength(String str,
                                            int length,
                                            String encoding) {
        if (isEmpty(encoding))
            encoding = "UTF-8";
        try {
            String tempStr = new String(str.getBytes(encoding),
                    "ISO-8859-1");
            int tLength = tempStr.length();
            if (length > tLength)
                length = tLength;
            return new String(tempStr.substring(0, length).getBytes(
                    "ISO-8859-1"), encoding);
        } catch (UnsupportedEncodingException e) {
            return str;
        }
    }

    /**
     * 转成INT 不能转换返回0
     *
     * @param v 字符
     * @return num
     */
    public static int toInt(String v) {
        if (!isEmpty(v)) {
            try {
                return Integer.parseInt(v.trim());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    /**
     * 是否是字母 是返回true
     *
     * @param v 字符
     * @return b
     */
    public static boolean isAlphabet(String v) {
        return !isEmpty(v) && v.matches("[[a-z]|[A-Z]]*");
    }

    /**
     * 是否是数字 是返回true
     *
     * @param v 字符
     * @return b
     */
    public static boolean isNum(String v) {
        return !isEmpty(v) && v.matches("[0-9]*");
    }

    public static Date getDate(String dtStr) {
        if (dtStr == null)
            return null;
        try {
            if (dtStr.trim().length() == 10) {
                dtStr = dtStr + " 00:00:00";
            } else if (dtStr.trim().length() > 19) {
                dtStr = dtStr.substring(0, 19);
            }
            SimpleDateFormat df = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss");
            return df.parse(dtStr);
        } catch (Exception ex) {
            return null;
        }

    }

    /**
     * 格式化小数位数
     * @param d d
     * @param u i
     * @return str
     */
    public static String format(double d, int u) {
        try {
            BigDecimal bigDecimal = new BigDecimal(d);
            return bigDecimal.setScale(u, BigDecimal.ROUND_HALF_UP).toString();
        } catch (Exception e) {
            return "-1";
        }
    }

    /**
     * 获取非空字符串，null返回""
     *
     * @param str str
     * @return str
     */
    public static String getNotNullValue(String str) {
        if (isEmpty(str))
            return "";
        else
            return str;
    }

    public static String getCNString(String str1, String encoding) {
        if (str1 != null) {
            if (isEmpty(encoding))
                encoding = "UTF-8";
            try {
                return new String(str1.getBytes("ISO-8859-1"), encoding);
            } catch (UnsupportedEncodingException e) {
                return str1;
            }
        }
        return null;
    }

    public static String getCNString(String cnText, String sourceEncode,
                                     String targetEncode) {
        if (isNotEmpty(cnText)) {
            if (isEmpty(sourceEncode))
                sourceEncode = "ISO-8859-1";
            if (isEmpty(targetEncode))
                targetEncode = "UTF-8";
            try {
                return new String(cnText.getBytes(sourceEncode), targetEncode);
            } catch (UnsupportedEncodingException e) {
                return cnText;
            }
        }
        return cnText;
    }

    /**
     * 判断是否为手机号
     *
     * @param mobiles phoneNum
     * @return b
     */
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern
                .compile("^((13[0-9])|(17[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    public static void putMap(Map<String, Object> map, String message, boolean flag, int status) {
        map.put("msg", message);
        map.put("success", flag);
        map.put("status", status);
    }

    /**
     * 时间维度
     *
     * @param cal c
     * @return i
     */
    public static int timeSk(Calendar cal) {
        int h = cal.get(Calendar.HOUR_OF_DAY);
        int m = cal.get(Calendar.MINUTE);
        int s = cal.get(Calendar.SECOND);
        return (h * 3600) + (m * 60) + s + 1;

    }

    /**
     * System.out.println(inet_ntoa(167772907));
     *
     * @param add num
     * @return 127.0.0.1
     */
    public static String inet_ntoa(long add) {
        return ((add & 0xff000000) >> 24) + "." + ((add & 0xff0000) >> 16)
                + "." + ((add & 0xff00) >> 8) + "." + ((add & 0xff));
    }

    public static long inet_aton(Inet4Address add) {
        byte[] bytes = add.getAddress();
        long result = 0;
        for (byte b : bytes) {
            if ((b & 0x80L) != 0) {
                result += 256L + b;
            } else {
                result += b;
            }
            result <<= 8;
        }
        result >>= 8;
        return result;
    }

    /**
     * System.out.println(inet_aton("10.0.2.235"));
     */
    public static Integer inet_aton(String add) {
        Integer result = 0;
        // number between a dot
        Integer section = 0;
        // which digit in a number
        int times = 1;
        // which section
        int dots = 0;
        for (int i = add.length() - 1; i >= 0; --i) {
            if (add.charAt(i) == '.') {
                times = 1;
                section <<= dots * 8;
                result += section;
                section = 0;
                ++dots;
            } else {
                section += (add.charAt(i) - '0') * times;
                times *= 10;
            }
        }
        section <<= dots * 8;
        result += section;
        return result;
    }

    /**
     * 处理异常信息并返回结果
     * try {
     * String str = null;
     * System.out.println(Integer.parseInt(str));
     * } catch (NumberFormatException e) {
     * System.out.println(getExceptionMessage(e));;
     * }
     *
     * @param e e
     * @return s
     */
    public static String getExceptionMessage(Exception e) {
        StringBuilder sb = new StringBuilder();
        StackTraceElement[] stacks = e.getStackTrace();
        for (StackTraceElement stack : stacks) {
            if (stack.getClassName().contains("com.wx") || stack.getClassName().contains("com.zyht")) {
                sb.append("class: ").append(stack.getClassName()).append("; method: ").append(stack.getMethodName()).append("; line: ").append(stack.getLineNumber())
                        .append(";  Exception: ");
                break;
            }
        }

        String message = e.toString();
        if (message.lastIndexOf(":") != -1)
            message = message.substring(0, message.lastIndexOf(":"));
        return sb.append(message).toString();
    }


    public static StringBuffer putLogInfo(Map<String, String> infoMap) {
        StringBuffer sb = null;

        if (isNotEmpty(infoMap)) {
            sb = new StringBuffer();

            for (Map.Entry<String, String> entry : infoMap.entrySet()) {
                if (sb.length() > 0) {
                    sb.append(",").append(entry.getKey()).append("=").append(entry.getValue());
                } else {
                    sb.append(entry.getKey()).append("=").append(entry.getValue());
                }
            }
        }
        return sb;
    }

    /**
     * 分割字符串并去空格
     *
     * @param str str
     * @param splitType splitType
     * @return List<String>
     */
    public static List<String> splitStr(String str, String splitType) {
        if (CommonUtils.isEmpty(str))
            return null;

        String[] ags = str.split(splitType);
        List<String> returnList = new ArrayList<String>();
        for (String word : ags) {
            // 排除搜索条件为空格的数据
            if (CommonUtils.isNotEmpty(word.trim())) {
                returnList.add(word.trim());
            }
        }
        if (CommonUtils.isNotEmpty(returnList)) {
            return returnList;
        }
        return null;
    }

    public static void putMap(Map<String, String> map, String status, String message, String esId) {
        map.put("status", status);
        map.put("msg", message);
        if (isNotEmpty(esId)) {
            map.put("esId", esId);
        }
    }

    public static String substring(String str, int start, int end) {
        if (str == null) {
            return null;
        } else {
            if (end < 0) {
                end += str.length();
            }

            if (start < 0) {
                start += str.length();
            }

            if (end > str.length()) {
                end = str.length();
            }

            if (start > end) {
                return "";
            } else {
                if (start < 0) {
                    start = 0;
                }

                if (end < 0) {
                    end = 0;
                }

                return str.substring(start, end);
            }
        }
    }
    
    public static List<String> parseList(String str) {
    	if (isNotEmpty(str)) {
    		String [] arr = str.split(",");
    		List<String> result = new ArrayList<>();
    		for (String s : arr) {
				if(isNotEmpty(s)){
					result.add(s.trim());
				}
			}
    		return result;
    	}
    	return new ArrayList<>();
    }

	public static void main(String[] args) throws IOException {
		// Java 8例子
		List<String> lines = Files.readAllLines(Paths.get("f:/json"), StandardCharsets.UTF_8);
		StringBuilder sb = new StringBuilder();
		for (String line : lines) {
			sb.append(line);
		}
		String fromFile = sb.toString();
		System.out.println(fromFile);
		
		
		JsonParser jsonParser = new JsonParser();
        JsonElement element = jsonParser.parse(fromFile);
        JsonObject jsonObj = element.getAsJsonObject();
        //fastjson 转换为集合对象
        ArrayList<Fans> list = (ArrayList<Fans>) JSON.parseArray(jsonObj.get("user_info_list").toString(), Fans.class);
		
		
        System.out.println(list.size());
		

	}
}
